﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ActionPluginAPI;
using System.Runtime.InteropServices;
using iMapa.Helper;
using System.IO;
using QuartzTypeLib;


namespace PlaySoundActionPlugin
{
    class PlaySoundActionPlugin:IActionPlugin
    {
       private static FilgraphManager mman;
       private static bool isOpen;
        
        public static void Close()
        {
            if (isOpen)
            {
                mman.StopWhenReady();
                Marshal.ReleaseComObject(mman);
            }
            isOpen = false;
        }

        public static void Open(string sFileName)
        {
            if (isOpen)
            {
                mman.StopWhenReady();
                Marshal.ReleaseComObject(mman);
            }
            mman = new FilgraphManager();
            mman.RenderFile(sFileName);
            isOpen = true;
        }

        public static void Play(bool loop)
        {
            if (isOpen)
            {
                IMediaControl ctrl = mman as IMediaControl;
                ctrl.Stop();
                ctrl.Run();
            }
        }

        public AbstractActionConfigPanel GetConfigPanel(IActionParameters properties)
        {
            return new PlaySoundActionConfigPanel(properties);
        }

        public string GetName()
        {
            return "Play Sound";
        }

        public IActionParameters GetNewParametersInstance(string RootPath)
        {
            return new PlaySoundActionParameters(RootPath);
        }

        public IActionParameters LoadFromFile(string filename)
        {
            PlaySoundActionParameters parameter= ObjectXMLSerializer<PlaySoundActionParameters>.Load(filename);
            parameter.RootPath= new FileInfo(filename).Directory.FullName+"\\";
            parameter.SetID(new FileInfo(filename).Name);
            return parameter;
        }

        public void Execute(IActionParameters parameters)
        {
            PlaySoundActionParameters psp= (PlaySoundActionParameters) parameters;
            Open(psp.SoundFile);
            Play(false);
        }
    }
}
